/*
 * Copyright 2010 Assert Developments
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.ad.coffeebreak.services;

import be.ad.coffeebreak.domain.User;
import org.apache.log4j.Logger;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;

/**
 * An implementation of user services.
 *
 * @author Stefan Bangels
 */
@Stateless
@SuppressWarnings("unused")
public class UsersServiceBean implements UsersService {

    private final Logger auditLogger = Logger.getLogger("audit");
    private final Logger logger = Logger.getLogger(getClass());

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public User findUserById(long userId) {
        return entityManager.find(User.class, userId);
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public List<User> findAllUsers() {
        return entityManager.createNamedQuery(User.QUERY_FIND_ALL_USERS, User.class).getResultList();
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public User findUserByEmail(String email) {
        if (email == null) {
            throw new IllegalArgumentException("email cannot be null");
        }
        try {
            TypedQuery<User> query = entityManager.createNamedQuery(User.QUERY_FIND_USER_BY_EMAIL, User.class);
            query.setParameter(User.QUERY_PARAM_EMAIL, email);
            return query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public User saveUser(User user) {
        if (user == null) {
            throw new IllegalArgumentException("user cannot be null");
        }
        return user.getId() == null ? insertUser(user) : updateUser(user);
    }

    /**
     * Create a user.
     * <p/>
     * User email, name, description, country, language, timezone, password are updated.
     * User creation date and modification date are filled with the current date/time.
     * A new user id is generated.
     *
     * @param user the user
     * @return the created user
     * @throws IllegalArgumentException when user, user#email, user#name or user#password is null
     */
    private User insertUser(User user) {
        if (user == null) {
            throw new IllegalArgumentException("user cannot be null");
        } else if (user.getEmail() == null) {
            throw new IllegalArgumentException("user e-mail cannot be null");
        } else if (user.getName() == null) {
            throw new IllegalArgumentException("user name cannot be null");
        }

        User tmp = new User();
        tmp.setEmail(user.getEmail());
        tmp.setName(user.getName());
        tmp.setCountry(user.getCountry());
        tmp.setLanguage(user.getLanguage());
        tmp.setTimeZone(user.getTimeZone());
        auditLogger.info("creating user: " + tmp);

        entityManager.persist(tmp);

        return tmp;
    }

    /**
     * Update user details.
     * <p/>
     * User name, description, country, language, timezone are updated.
     * User id, email, creation date, password remain the same.
     * User modification date is filled with the current date/time.
     *
     * @param user the user
     * @return the updated user
     * @throws IllegalArgumentException when user, user#name or user#email is null
     */
    private User updateUser(User user) {
        if (user == null) {
            throw new IllegalArgumentException("user cannot be null");
        } else if (user.getName() == null) {
            throw new IllegalArgumentException("user name cannot be null");
        } else if (user.getId() == null) {
            throw new IllegalArgumentException("user e-mail cannot be null");
        }

        User tmp = findUserById(user.getId());
        tmp.setName(user.getName());
        tmp.setCountry(user.getCountry());
        tmp.setLanguage(user.getLanguage());
        tmp.setTimeZone(user.getTimeZone());
        auditLogger.info("updating user: " + tmp);

        return tmp;
    }

    @Override
    public void deleteUser(long userId) {
        User user = findUserById(userId);
        if (user != null) {
            auditLogger.info("deleting user: " + user);
            entityManager.remove(user);
        } else {
            logger.warn("error while deleting user, user not found! (id=" + userId + ")");
        }
    }


}
